package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"yun_image/config/api"
	"yun_image/util"
)

// ipFrequency 检测ip请求是否过于频繁
func ipFrequency(context *gin.Context) {
	if util.IndexOf[string](api.FrequencyLimitExcludePaths, context.FullPath(), len(api.FrequencyLimitExcludePaths)) != -1 {
		context.Next()
		return
	}
	util.IpFrequencyRecord.Add(context.ClientIP())
	if util.IpFrequencyRecord.Check(context.ClientIP()) {
		context.JSON(http.StatusOK, gin.H{
			"tooFrequent": true,
		})
		context.Abort()
		return
	} else {
		context.Next()
	}
}

func UseIpLimit(router *gin.Engine) {
	router.Use(ipFrequency)
}
